package concurrent;

import java.util.concurrent.locks.ReentrantLock;


/**
 * lock() 获得锁， 如果所已被占用，则等待
 * lockInterruptibly()  获得锁， 但优先响应中断,
 * tryLock() 尝试获得锁， 如果成功，返回true，否则false
 * tryLock(long time, TimeUnit unit)  在指定时间内尝试
 * unlock() 释放锁
 */

public class ReenterLock implements Runnable {

    public static ReentrantLock lock = new ReentrantLock();
    public static int i=0;

    @Override
    public void run() {
        for (int j=0; j<10000000; j++) {
            lock.lock();
            try {
                i++;
            }finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReenterLock reenterLock = new ReenterLock();
        Thread t1 = new Thread(reenterLock);
        Thread t2 = new Thread(reenterLock);

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(i);

    }

}
